namespace TransformCodeGenerator
{
  using System;
  using System.IO;
  using System.Xml;

  internal class TransformCodeGeneratorXmlResolver : XmlUrlResolver
  {

    readonly string[] _searchPaths;

    public TransformCodeGeneratorXmlResolver(string[] searchPaths)
    {
      _searchPaths = searchPaths;
    }

    public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
    {
      if(absoluteUri.IsFile)
      {

        // file exists?
        if (!File.Exists(absoluteUri.LocalPath))
        {

          // HACK: is there a better way to get the filename portion?
          string[] seqs = absoluteUri.Segments;
          string fileName = seqs[seqs.Length - 1];

          foreach (string searchPath in _searchPaths)
          {
            try
            {
              string fullFileName = Path.Combine(searchPath, fileName);
              return base.GetEntity(new Uri(fullFileName), role, ofObjectToReturn);
            }
            catch (FileNotFoundException)
            {
              // ignore
            }
          }

        }

      }
      return base.GetEntity(absoluteUri, role, ofObjectToReturn);
    } 

  }
}
